<template>
  <div class="parking-usage-add-container">
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><Promotion /></el-icon>
            <span>{{ isEdit ? '编辑车位使用记录' : '添加车位使用记录' }}</span>
          </div>
          <div class="header-operations">
            <el-button @click="goBack" plain>
              <el-icon><Back /></el-icon>返回列表
            </el-button>
          </div>
        </div>
      </template>

        <el-form
        :model="parkingUsageForm" 
          :rules="rules"
        ref="parkingUsageFormRef"
        label-position="top"
        class="usage-form"
        v-loading="loading"
      >
        <div class="form-divider">
          <el-divider content-position="left">
            <el-icon><House /></el-icon>
            <span>小区和车位信息</span>
          </el-divider>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="小区" prop="communityId">
              <el-select 
                v-model="parkingUsageForm.communityId" 
                placeholder="请选择小区"
                filterable
                clearable
                class="form-select"
              >
              <el-option 
                  v-for="item in communities" 
                  :key="item.id" 
                  :label="item.name" 
                  :value="item.id">
                </el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="车位" prop="parkingId">
              <el-select 
                v-model="parkingUsageForm.parkingId" 
                placeholder="请选择车位"
                filterable
                clearable
                :disabled="!parkingUsageForm.communityId"
                class="form-select"
              >
              <el-option 
                  v-for="item in availableParkings" 
                  :key="item.id" 
                  :label="item.name + ' - ' + item.type" 
                  :value="item.id"
                  :disabled="item.status === '已使用' && !isEditingSameParkingId(item.id)">
                  <div class="parking-option">
                    <span>{{ item.name }}</span>
                    <span class="parking-type">{{ item.type }}</span>
                    <el-tag 
                      size="small" 
                      :type="item.status === '空闲' ? 'success' : 'danger'"
                      style="margin-left: 10px;">
                      {{ item.status }}
                    </el-tag>
                  </div>
                </el-option>
            </el-select>
          </el-form-item>
          </el-col>
        </el-row>

        <div class="form-divider">
          <el-divider content-position="left">
            <el-icon><User /></el-icon>
            <span>业主和车辆信息</span>
          </el-divider>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
          <el-form-item label="业主" prop="ownerId">
              <el-select 
                v-model="parkingUsageForm.ownerId" 
                placeholder="请选择业主"
                filterable
                clearable
                class="form-select"
                @change="handleOwnerChange"
              >
              <el-option 
                  v-for="item in owners" 
                  :key="item.id" 
                  :label="item.name + (item.phoneNumber ? ' - ' + item.phoneNumber : '')" 
                  :value="item.id">
                  <div class="owner-option">
                    <span>{{ item.name }}</span>
                    <span class="owner-phone" v-if="item.phoneNumber">{{ item.phoneNumber }}</span>
                  </div>
                </el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="车辆" prop="vehicleId">
              <el-select 
                v-model="parkingUsageForm.vehicleId" 
                placeholder="请选择车辆"
                filterable
                clearable
                :disabled="!parkingUsageForm.ownerId"
                class="form-select"
              >
              <el-option 
                  v-for="item in ownerVehicles" 
                  :key="item.id" 
                  :label="item.licensePlate + ' - ' + (item.brand || '未知品牌')" 
                  :value="item.id">
                  <div class="vehicle-option">
                    <span class="vehicle-plate">{{ item.licensePlate }}</span>
                    <span>{{ item.brand }} {{ item.model }}</span>
                  </div>
                </el-option>
            </el-select>
          </el-form-item>
          </el-col>
        </el-row>

        <div class="form-divider">
          <el-divider content-position="left">
            <el-icon><Money /></el-icon>
            <span>使用信息</span>
          </el-divider>
        </div>

        <el-row :gutter="20">
          <el-col :span="8">
          <el-form-item label="使用类型" prop="usageType">
              <el-select v-model="parkingUsageForm.usageType" placeholder="请选择使用类型" class="form-select">
                <el-option label="租用" :value="1"></el-option>
                <el-option label="购买" :value="2"></el-option>
                <el-option label="临时" :value="3"></el-option>
              </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="起始日期" prop="startDate">
            <el-date-picker
                v-model="parkingUsageForm.startDate" 
              type="date"
              placeholder="选择开始日期"
                class="form-select">
              </el-date-picker>
          </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
                v-model="parkingUsageForm.endDate" 
              type="date"
              placeholder="选择结束日期"
                class="form-select"
                :disabled="parkingUsageForm.usageType === 2">
              </el-date-picker>
          </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="费用（元）" prop="fee">
              <el-input-number v-model="parkingUsageForm.fee" :min="0" :precision="2" :step="100" class="form-input"></el-input-number>
          </el-form-item>
          </el-col>
          <el-col :span="8">
          <el-form-item label="支付状态" prop="paymentStatus">
              <el-select v-model="parkingUsageForm.paymentStatus" placeholder="请选择支付状态" class="form-select">
              <el-option label="未支付" value="未支付"></el-option>
              <el-option label="已支付" value="已支付"></el-option>
            </el-select>
          </el-form-item>
          </el-col>
        </el-row>

          <el-form-item label="备注" prop="remarks">
          <el-input 
            v-model="parkingUsageForm.remarks" 
            type="textarea" 
            rows="3" 
            placeholder="请输入备注信息"
            class="form-input">
          </el-input>
          </el-form-item>

        <el-form-item class="form-buttons">
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '保存修改' : '提交' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
    </el-card>
  </div>
</template>

<script>
import { 
  Promotion,
  Back, 
  House, 
  User, 
  Money,
  Calendar
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

export default {
  name: 'ParkingUsageAdd',
  components: {
    Promotion,
    Back,
    House,
    User,
    Money,
    Calendar
  },
  data() {
    return {
      parkingUsageForm: {
        communityId: '',
        parkingId: '',
        ownerId: '',
        vehicleId: '',
        usageType: 1,
        startDate: new Date(),
        endDate: null,
        fee: 0,
        paymentStatus: '未支付',
        remarks: ''
      },
      communities: [],
      allParkings: [],
      availableParkings: [],
      owners: [],
      ownerVehicles: [],
      loading: false,
      submitting: false,
      isEdit: false,
      originalParkingId: null,
      recordId: null,
      rules: {
        communityId: [{ required: true, message: '请选择小区', trigger: 'change' }],
        parkingId: [{ required: true, message: '请选择车位', trigger: 'change' }],
        ownerId: [{ required: true, message: '请选择业主', trigger: 'change' }],
        usageType: [{ required: true, message: '请选择使用类型', trigger: 'change' }],
        startDate: [{ required: true, message: '请选择起始日期', trigger: 'change' }],
        endDate: [
          { 
            validator: (rule, value, callback) => {
              if (this.parkingUsageForm.usageType !== 2 && !value) {
                callback(new Error('请选择结束日期'));
              } else if (value && this.parkingUsageForm.startDate && value < this.parkingUsageForm.startDate) {
                callback(new Error('结束日期不能早于开始日期'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        fee: [{ required: true, message: '请输入费用', trigger: 'blur' }],
        paymentStatus: [{ required: true, message: '请选择支付状态', trigger: 'change' }]
      }
    };
  },
  created() {
    // 检查是否为编辑模式
    const id = this.$route.query.id;
    if (id) {
      this.isEdit = true;
      this.recordId = id;
      this.fetchParkingUsage(id);
    }
    
    this.fetchCommunities();
    this.fetchOwners();
  },
  watch: {
    'parkingUsageForm.communityId': function(newVal) {
      if (newVal) {
        this.fetchParkingsByCommunityId(newVal);
      } else {
        this.availableParkings = [];
        this.parkingUsageForm.parkingId = '';
      }
    },
    'parkingUsageForm.usageType': function(newVal) {
      if (newVal === 2) {
        this.parkingUsageForm.endDate = null;
      }
    }
  },
  methods: {
    async fetchParkingUsage(id) {
      try {
        this.loading = true;
        const response = await axios.get(`/api/parking-usages/${id}`);
        const parkingUsage = response.data;
        
        // 保存原始车位ID以进行编辑检查
        this.originalParkingId = parkingUsage.parkingId;
        
        // 填充表单
        this.parkingUsageForm = {
          communityId: parkingUsage.communityId,
          parkingId: parkingUsage.parkingId,
          ownerId: parkingUsage.ownerId,
          vehicleId: parkingUsage.vehicleId,
          usageType: parkingUsage.usageType,
          startDate: parkingUsage.startDate ? new Date(parkingUsage.startDate) : null,
          endDate: parkingUsage.endDate ? new Date(parkingUsage.endDate) : null,
          fee: parkingUsage.fee,
          paymentStatus: parkingUsage.paymentStatus,
          remarks: parkingUsage.remarks
        };
        
        // 如果有业主ID，获取该业主的车辆列表
        if (parkingUsage.ownerId) {
          this.fetchVehiclesByOwnerId(parkingUsage.ownerId);
        }
      } catch (error) {
        console.error('获取车位使用记录失败:', error);
        ElMessage.error('获取车位使用记录失败');
      } finally {
        this.loading = false;
      }
    },
    
    async fetchCommunities() {
      try {
        this.loading = true;
        const response = await axios.get('/api/communities');
        this.communities = response.data;
      } catch (error) {
        console.error('获取小区列表失败:', error);
        ElMessage.error('获取小区列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    async fetchParkingsByCommunityId(communityId) {
      try {
        this.loading = true;
        const response = await axios.get(`/api/parkings/community/${communityId}`);
        this.allParkings = response.data;
        this.availableParkings = this.allParkings;
      } catch (error) {
        console.error('获取车位列表失败:', error);
        ElMessage.error('获取车位列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    async fetchOwners() {
      try {
        this.loading = true;
        const response = await axios.get('/api/owners');
        this.owners = response.data;
      } catch (error) {
        console.error('获取业主列表失败:', error);
        ElMessage.error('获取业主列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    async fetchVehiclesByOwnerId(ownerId) {
      if (!ownerId) {
        this.ownerVehicles = [];
        this.parkingUsageForm.vehicleId = '';
        return;
      }
      
      try {
        this.loading = true;
        const response = await axios.get(`/api/vehicles/owner/${ownerId}`);
        this.ownerVehicles = response.data;
      } catch (error) {
        console.error('获取车辆列表失败:', error);
        ElMessage.error('获取车辆列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    handleOwnerChange(ownerId) {
      this.fetchVehiclesByOwnerId(ownerId);
      this.parkingUsageForm.vehicleId = '';
    },
    
    isEditingSameParkingId(parkingId) {
      return this.isEdit && this.originalParkingId === parkingId;
    },
    
    goBack() {
      this.$router.push('/property/parking/usage');
    },
    
    submitForm() {
      this.$refs.parkingUsageFormRef.validate(async (valid) => {
        if (valid) {
          try {
            this.submitting = true;
            
            // 准备要提交的数据
            const parkingUsage = {
              parking: { id: this.parkingUsageForm.parkingId },
              owner: { id: this.parkingUsageForm.ownerId }
            };
            
            // 如果有选择车辆，添加到提交数据中
            if (this.parkingUsageForm.vehicleId) {
              parkingUsage.vehicle = { id: this.parkingUsageForm.vehicleId };
            } else {
              // 如果没有选择车辆，设置为null而不是省略该字段
              parkingUsage.vehicle = null;
            }
            
            // 添加其他字段
            parkingUsage.usageType = this.parkingUsageForm.usageType;
            parkingUsage.startDate = this.parkingUsageForm.startDate;
            parkingUsage.endDate = this.parkingUsageForm.endDate;
            parkingUsage.fee = this.parkingUsageForm.fee;
            parkingUsage.paymentStatus = this.parkingUsageForm.paymentStatus;
            parkingUsage.remarks = this.parkingUsageForm.remarks || '';
            
            console.log('提交的数据:', JSON.stringify(parkingUsage));
            
            let response;
            if (this.isEdit) {
              // 更新现有记录
              response = await axios.put(`/api/parking-usages/${this.recordId}`, parkingUsage);
              ElMessage.success('车位使用记录更新成功');
            } else {
              // 创建新记录
              response = await axios.post('/api/parking-usages', parkingUsage);
              ElMessage.success('车位使用记录创建成功');
            }
            
            console.log('服务器响应:', response.data);
            
            // 返回列表页
            setTimeout(() => {
              this.$router.push('/property/parking/usage');
            }, 1000);
          } catch (error) {
            console.error(this.isEdit ? '更新失败:' : '创建失败:', error);
            
            // 详细的错误信息处理
            let errorMessage = this.isEdit ? '更新车位使用记录失败' : '创建车位使用记录失败';
            
            if (error.response) {
              console.error('错误状态码:', error.response.status);
              console.error('错误数据:', error.response.data);
              
              if (error.response.data && error.response.data.message) {
                errorMessage = error.response.data.message;
              } else if (error.response.status === 400) {
                errorMessage += ' - 请求数据格式不正确';
              } else if (error.response.status === 409) {
                errorMessage += ' - 该车位已被占用';
              } else if (error.response.status === 403) {
                errorMessage += ' - 没有操作权限';
              }
            }
            
            ElMessage.error(errorMessage);
          } finally {
            this.submitting = false;
          }
        } else {
          ElMessage.warning('请填写完整的表单信息');
          return false;
        }
      });
    },
    
    resetForm() {
      if (this.isEdit) {
        // 编辑模式下，重新获取原始数据
        this.fetchParkingUsage(this.recordId);
      } else {
        // 新增模式下，重置为空表单
        this.$refs.parkingUsageFormRef.resetFields();
        this.parkingUsageForm = {
          communityId: '',
          parkingId: '',
          ownerId: '',
          vehicleId: '',
          usageType: 1,
          startDate: new Date(),
          endDate: null,
          fee: 0,
          paymentStatus: '未支付',
          remarks: ''
        };
      }
    }
  }
};
</script>

<style scoped>
.parking-usage-add-container {
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.header-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
  color: #409EFF;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.usage-form {
  padding: 20px;
}

.form-divider {
  margin: 10px 0 20px;
}

.form-divider .el-divider__text {
  display: flex;
  align-items: center;
  font-weight: bold;
  color: #606266;
}

.form-divider .el-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #409EFF;
}

.form-select {
  width: 100%;
}

.form-input {
  width: 100%;
}

.form-buttons {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 下拉选项样式 */
.parking-option,
.owner-option,
.vehicle-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.parking-type,
.owner-phone {
  color: #909399;
  margin-left: 10px;
}

.vehicle-plate {
  font-weight: bold;
  margin-right: 10px;
}
</style>